package be.vdab.gwt.cultuurhuis.server;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import be.vdab.gwt.cultuurhuis.client.CultuurhuisService;
import be.vdab.gwt.cultuurhuis.shared.FieldVerifier;
import be.vdab.gwt.cultuurhuis.shared.entities.Voorstelling;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class CultuurhuisServiceImpl extends RemoteServiceServlet implements
		CultuurhuisService {


	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}

	@Override
	public List<Voorstelling> getVoorstellingen()
			throws IllegalArgumentException {
		EntityManager em =  EMF.get().createEntityManager();
		
		Query q = em.createQuery("select from " + Voorstelling.class.getName());
		
		List<Voorstelling> attached = q.getResultList();
			
		List<Voorstelling> detached = clone(attached);
		
		
		em.close();
		
		return detached;
	}

	@Override
	public Voorstelling addVoorstelling(Voorstelling v) {
		EntityManager em =  EMF.get().createEntityManager();
		
		em.persist(v);
		
		em.close();		
		
		return v;
	}
	
	private <X> List<X> clone (List<X> list){
		List<X> result = new LinkedList<X>();
		for(X item : list){
			result.add(item);
		}
		return result;
	}

	@Override
	public Voorstelling saveVoorstelling(Voorstelling v) {
		EntityManager em =  EMF.get().createEntityManager();
		
		em.persist(v);
		
		em.close();		
		
		return v;	
	}
}
